
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function wxPromisify(fn) {
  return function (obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function (res) {
        resolve(res)
      }
      obj.fail = function (res) {
        reject(res)
      }
      fn(obj)
    })
  }
}

//验证是否是手机号码
function vailPhone(number) {
  let flag = false;
  let myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
  if (number.length != 11) {
    flag = flag;
  } else if (!myreg.test(number)) {
    flag = flag;
  } else {
    flag = true;
  }
  return flag;
}


function authori(e) {
  if (checkChoseImages(e.path)) {
    console.log('选择图片页面不做页面跳转判断,不做名片id的缓存'); 
    return;
  }
  let plist = '';  
  let params = decodeURIComponent(e.query.scene);
  console.log('二维码参数', params);  
  if (params && params != 'undefined') {
    if (params.indexOf('p-') != -1) {
      let param = params.match(/p-(\S*)/)[1];//参数
      plist = param.split('_');
    } else {
      let param = params.match(/p=(\S*)/)[1];//参数
      plist = param.toString().split('#');
    }
  }
  
  if (plist[0]) {
    wx.setStorageSync("cardId", plist[0]);      //扫描二维码方式
  } else if (JSON.stringify(e.query) != "{}") {
    if (e.query.id) {
      wx.setStorageSync("cardId", e.query.id)   //转发方式
    }
  }

  //名片首页
  if(e.path == "pages/index/index"){  
    var cardId = wx.getStorageSync("cardId");  //默认方式(自己的名片)
    if (cardId == "" || cardId == null) {
      console.log('未找到名片,加载自己的名片')
      getStaffIdByUid(function (staff) {
        if (staff.Id > 0) {
          wx.setStorageSync("cardId", staff.Id);
        } else {
          wx.reLaunch({url: '/pages/indexDefault/index'})
        }
      });
    }
  }
}

// //判断是否创建过名片
// function getStaffIdByUid(cb) {
//   var app = getApp();
//   let staffid = 0;
//   if (app.globalData.userInfo) {
//     wx.request({
//       url: app.globalData.host + '/api/Staff/GetStaffIdByUid?Uid=' + app.globalData.userInfo.Uid,
//       success: function (res) {
//         if (res.data.Code == 0) {
//           if (res.data.Data) {
//             staffid = res.data.Data.Id;
//           }
//           cb(staffid);
//         }
//       },
//     })
//   } else {
//     setTimeout(function () {
//       getStaffIdByUid(cb)
//     }, 1000)
//   }
// }

//授权验证(登陆规范修改后的)
function isAccredit(cb) {
  let isAccredit = false;
  var app = getApp();
  if (app.globalData.userInfo && app.globalData.userInfo.Avatar.indexOf('userdefault.png') == -1) {
    isAccredit = true;
  }
  cb(isAccredit);
}

//判断是否是选择图片页面
function checkChoseImages(path) {
  var isChoose = false;
  var pathList = ["pages/weijieke/product/index", "pages/weijieke/editorCard/index", "pages/weijieke/myPhoto/index", "pages/weijieke/sendState/index", "pages/h5page/index", "pages/weijieke/states/index", "pages/classes-new/index", "pages/about/index", "pages/weijieke/editorCompany/index", "merchant/merchants/addProject/index", "merchant/merchants/addCoupon/index", "merchant/merchants/addVipcard/index", "live/apply/index"]
  for (let i = 0; i < pathList.length; i++) {
    if (pathList[i] == path) {
      isChoose = true;
      break;
    }
  }
  return isChoose;
}

/**
 * 会员的操作记录
 * 参数actionType:2 转发名片, 3 复制微信, 7 保存电话, 9 拨打电话
 */
function aiCardActionRecord(actionType) {
  var app = getApp();
  var cardId = wx.getStorageSync("cardId");
  if (!app.globalData.userInfo) {
    return;
  }
  if (cardId) {
    wx.request({
      url: app.globalData.host + '/api/BusinessCard/AddAiCardAction?staffId=' + cardId + '&uid=' + app.globalData.userInfo.Uid + '&actionType=' + actionType + '&storeId=' + app.globalData.storeId,
      success: function (res) {
        if (res.data.Code == 0) {
        }
      },
    })
  }
}

//判断两个时间比较大小
function compareDate(d1, d2) {
  return ((new Date(d1.replace(/-/g, "\/"))) > (new Date(d2.replace(/-/g, "\/"))));
}

//当前时间获取
function getCurrentToday() {
  const date = new Date()
  var year = date.getFullYear();
  var mouths = (date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : (date.getMonth() + 1);
  var day = date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate();
  var hours = date.getHours();
  var Minutes = date.getMinutes(); //当前分
  var currentdate = year + "-" + mouths + "-" + day + "\t" + hours + ":" + Minutes;
  return currentdate
}

//当前时间获取2
function getCurrentTodayDate() {
  const date = new Date()
  var year = date.getFullYear();
  var mouths = (date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : (date.getMonth() + 1);
  var day = date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate();
  var hours = date.getHours() < 10 ? ("0" + date.getHours()) : date.getHours();
  var Minutes = date.getMinutes() < 10 ? ("0" + date.getMinutes()) : date.getMinutes(); //当前分
  var getSeconds = date.getSeconds() < 10 ? ("0" + date.getSeconds()) : date.getSeconds();
  var currentdate = year + "/" + mouths + "/" + day + "\t" + hours + ":" + Minutes + ":" + getSeconds;
  return currentdate
}

/**
 * 传入时间后几天
 * param：传入时间：dates:"2018-04-02",later:往后多少天
 */
function dateLater(dates, later) {
  let dateObj = {};
  let show_day = new Array('周日', '周一', '周二', '周三', '周四', '周五', '周六');
  let date = new Date(dates);
  date.setDate(date.getDate() + later);
  let day = date.getDay();
  dateObj.dates = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1) + "月" + (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate()) + "日";
  dateObj.newdates = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1) + "-" + (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate());
  dateObj.year = date.getFullYear();
  dateObj.month = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1);
  dateObj.day = (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate());
  dateObj.week = show_day[day];
  return dateObj;
}

// 当前时间加一天得到新日期
function jiaDate(dataStr, dayCount) {
  var strdate = dataStr; //日期字符串
  var isdate = new Date(strdate.replace(/-/g, "/")); //把日期字符串转换成日期格式
  isdate = new Date((isdate / 1000 + (86400 * dayCount)) * 1000); //日期加1天
  // var pdate = isdate.getFullYear() + "-" + (isdate.getMonth() + 1) + "-" + (isdate.getDate());
  return isdate;
}

// 当前时间减一天得到新日期
function jianDate(dataStr, dayCount) {
  var strdate = dataStr; //日期字符串
  var isdate = new Date(strdate.replace(/-/g, "/")); //把日期字符串转换成日期格式
  isdate = new Date((isdate / 1000 - (86400 * dayCount)) * 1000); //日期减1天
  return isdate;
}

//获取手机号
function getMobile(e, callback) {
  var app = getApp();
  if(!e.detail.encryptedData) {
    console.log(e.detail)
    return;
  }
  wx.login({
    success: function (res) {
      var code = res.code;
      wx.request({
        url: app.globalData.host + '/api/account/getphonenumber?encryptedData=' + encodeURIComponent(e.detail.encryptedData) + '&iv=' + encodeURIComponent(e.detail.iv) + '&storeid=' + app.globalData.storeId + '&storeAppId=' + app.globalData.storeAppId + "&code=" + code,
        success: function (res) {
          console.log('授权手机号结果', res);
          if (res.data.Code == 0) {
            app.globalData.userInfo.Mobile = res.data.Data;
            wx.setStorageSync("mobile", res.data.Data);
            if (callback) {
              callback(res.data.Data)
            }
          } else {
            if (callback) {
              callback(null);
            }
            wx.showModal({
              title: '提示',
              content: res.data.Message,
              showCancel: false
            })
          }
        },
      })
    }
  })
}

//图片路径拼接
function formatAvater(avater, imgPath) {
  if (avater != null && avater.indexOf("http") == 0) {
    return avater;
  } else {
    return imgPath + avater;
  }
}

//图片路径拼接(商品头图)
function formatAvaterByProHead(avater) {
  const app = getApp();
  if (avater != null && avater.indexOf("http") == 0) {
    return avater;
  } else {
    return 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/show/source/' + avater;
  }
}

//记录产品和商圈停留时间
function recordActionTime(startDate, actionType, typeId) {
  var app = getApp();
  if (!app.globalData.userInfo) {
    return;
  }
  var cardId = wx.getStorageSync("cardId")
  var endDate = formatTime(new Date());
  var d1 = new Date(startDate);
  var d2 = new Date(endDate);
  var seconds = parseInt(d2 - d1) / 1000
  var data = {
    storeId: app.globalData.storeId,
    staffId: cardId,
    actionType: actionType, //会员的操作(5 查看商圈,22 查看产品详情)
    typeId: typeId, //操作对应的ID (actiontype=5 商圈ID, actiontype=22 产品ID)
    seconds: seconds, //记录时间秒
    uid: app.globalData.userInfo.Uid
  }

  wx.request({
    url: app.globalData.host + '/api/BusinessCard/AddActionTime',
    data: data,
    success: function (res) { },
  })
}

//根据底部导航设置头部文字
function setNavBarTitle(e, currePage) {
  let newTabbar = e.detail.newTabbar;
  if (!newTabbar) {
    return;
  }
  for (let i = 0; i < newTabbar.length; i++) {
    if (newTabbar[i].pagePath == currePage) {
      wx.setNavigationBarTitle({
        title: e.detail.newTabbar[i].text
      })
    }
  }
}

//获取底部导航设置头部文字
function getNavBarTitle(e, currePage) {
  let newTabbar = e.detail.newTabbar;
  let title = '';
  if (!newTabbar) {
    return;
  }
  for (let i = 0; i < newTabbar.length; i++) {
    if (newTabbar[i].pagePath == currePage) {
      title = e.detail.newTabbar[i].text;
      break;
    }
  }
  return title;
}
//获取当前客户端平台
function getMobileSysInfo(cb) {
  wx.getSystemInfo({
    success(res) {
      cb(res.platform)
    }
  })
}

//订阅消息弹窗tmplIds
function subscribe() {  
  wx.getSetting({
    withSubscriptions: true,
    success(res) {
      getTemplate((tmplIds)=>{
        if (tmplIds.length > 0) {
          wx.requestSubscribeMessage({
            tmplIds: tmplIds,
            success(res) {
              console.log('订阅完成', res);
            }
          })
        }
      })
    }
  })
}
//获取模板通知id
function getTemplate(callback){
  let tmplIds = wx.getStorageSync("tmplIds");
  if(tmplIds){
    console.log('缓存中订阅',tmplIds)
    callback(tmplIds); return;
  }
  var app = getApp();
  wx.request({
    url: app.globalData.host + '/api/weapp/GetTemplateId?storeAppId=' + app.globalData.storeAppId,
    success: function (res) {
      tmplIds = [];
      for (let i = 0; i < res.data.Data.tmplIds.length; i++) {
        if(tmplIds.length<3){
          tmplIds.push(res.data.Data.tmplIds[i]);
        }
      }
      wx.setStorageSync("tmplIds",tmplIds);
      callback(tmplIds);
    }
  })
}
//获取未读消息
function getMsgUnRead(staffUId, callback) {
  var app = getApp();
  if(!app.globalData.userInfo) return;
  wx.request({
    url: app.globalData.host + '/api/im/GetUnReadByOpenId?fromopenid=' + app.globalData.userInfo.Uid + '&toopenid=' + staffUId,
    success: function (res) {
      if (res.data.Code == 0) {
        callback(res.data.Data)
      }
    }
  })
}

// 点击顶部的消息弹窗跳转聊天
function tapChatFrom(cardInfo) {
  var app = getApp();
  let nickname = cardInfo.Name;
  wx.request({
    url: app.globalData.host + '/api/IM/UserByOpenId?openId=' + app.globalData.userInfo.Uid,
    success: function (res) {
      if (res.data.Code == 0 && res.data.Data) {
        let fromuid = res.data.Data.Id;
        wx.request({
          url: app.globalData.host + '/api/IM/UserByOpenId?openId=' + cardInfo.Uid,
          success: function (res2) {
            if (res2.data.Code == 0 && res2.data.Data) {
              let touid = res2.data.Data.Id;
              let chatparam = 'touid=' + touid + '&fromuid=' + fromuid + '&nickname=' + nickname + '&storeid=' + app.globalData.storeId;
              wx.navigateTo({
                url: '/pages/h5page/index?url=sessionDetail.html&chatparam=' + encodeURIComponent(chatparam),
              })
            }
          }
        })
      }
    }
  })
}

// 关闭socket连接
function toCloseSocket() {
  console.log('关闭socket连接===');
  wx.closeSocket();
  wx.onSocketClose(function (res) {
    console.log('WebSocket 已关闭！', res)
  })
}

// 复制
function copyData(str, tip) {
  wx.setClipboardData({
    data: str,
    success(res) {
      wx.showToast({
        title: tip + '已复制',
      })
    }
  })
}

// 授权微信头像昵称
function AuthorizeUserInfoOld(e, loginCode, cb = '') {
  var app = getApp();
  var iv = e.detail.iv;
  var encryptedData = e.detail.encryptedData;
  let regioster = false;
  let codes = loginCode
  if (codes == '') {
    wx.login({
      success: (ress) => {
        codes = ress.code;
      },
    })
  }
  // 下面开始调用注册接口
  wx.request({
    url: app.globalData.host + '/api/account/WxOpenRegister',
    data: {
      code: codes,
      encryptedData: encryptedData,
      iv: iv,
      storeid: app.globalData.storeId,
      storeAppId: app.globalData.storeAppId
    }, // 设置请求的 参数
    method: 'POST',
    success: (ress) => {
      if (ress.data.Code == 0) {
        regioster = true;
        getUserInfoAgain(app.globalData.userInfo.Uid);//更新头像昵称后重新获取
      } else {
        wx.showModal({
          title: '提示',
          content: ress.data.Message,
          showCancel: false
        })
      }
      if (cb) {
        cb(regioster);
      }
    }
  })
}

// 授权微信头像昵称(新版)
function AuthorizeUserInfo(e, loginCode, cb = '') {
  var app = getApp();
  var iv = e.iv;
  var encryptedData = e.encryptedData;
  let regioster = false;
  let codes = loginCode;
  if (!encryptedData) {
    console.log('授权头像昵称')
    if (e.userInfo && e.userInfo.avatarUrl) {
      wx.request({
        url: app.globalData.host + '/api/account/WxOpenRegister',
        data: {
          code: '',
          encryptedData: '',
          iv: '',
          nickName: e.userInfo.nickName,
          avatar: e.userInfo.avatarUrl,
          uid: app.globalData.userInfo.Uid,
          storeid: app.globalData.storeId,
          storeAppId: app.globalData.storeAppId
        }, // 设置请求的 参数
        method: 'POST',
        success: (ress) => {
          if (ress.data.Code == 0) {
            regioster = true;
            getUserInfoAgain(app.globalData.userInfo.Uid);//更新头像昵称后重新获取
          } else {
            wx.showModal({
              title: '提示',
              content: ress.data.Message,
              showCancel: false
            })
          }
          if (cb) {
            cb(regioster);
          }
        }
      })
    }
    return;
  }
  console.log('授权头像昵称2')
  wx.login({
    success: (result) => {
      codes = result.code;
      wx.request({
        url: app.globalData.host + '/api/account/WxOpenRegister',
        data: {
          code: codes,
          encryptedData: encryptedData,
          iv: iv,
          storeid: app.globalData.storeId,
          storeAppId: app.globalData.storeAppId
        },
        method: 'POST',
        success: (ress) => {
          if (ress.data.Code == 0) {
            regioster = true;
            getUserInfoAgain(app.globalData.userInfo.Uid);//更新头像昵称后重新获取
          } else {
            wx.showModal({
              title: '提示',
              content: ress.data.Message,
              showCancel: false
            })
          }
          if (cb) {
            cb(regioster);
          }
        }
      })
    },
    fail: (res) => {
      if (cb) {
        cb(regioster);
      }
    }
  })
}

function getUserInfoAgain(uid) {
  var app = getApp();
  wx.request({
    url: app.globalData.host + '/api/User/GetUserInfo?uid=' + uid,
    success: function (res) {
      if (res.data.Code == 0) {
        app.globalData.userInfo = res.data.Data.UserInfo
      }
    }
  })
}

//获取url参数值: name：参数名
function getQuery(url, name) {
  url = url.indexOf('?')>-1 ? url.substr(url.indexOf('?')+1) : url;
  var arr = url.split('&');
  for(var i = 0; i < arr.length; i++) {
      var ar = arr[i].split('=');
      if (ar[0] == name) {
          if (unescape(ar[1]) == 'undefined') {
            return '';
          } else {
            return unescape(ar[1]);
          }
      }
  }
  return '';
}

function showModal(content){
  wx.showModal({
    title: '提示',
    content: content,
    showCancel: false
  })
}
function showToast(title,icon = 'none'){
  wx.showToast({
    title: title,
    icon: icon
  })
}
function confirm(content,success){
  wx.showModal({
    title: '提示',
    content: content,
    success: function (res) {
      if (res.confirm) {
        success();
      }
    }
  })
}
//当前定位
function getLocation(callback,isFlush=0){
  let location = wx.getStorageSync("location");
  if(!location){
    location = {lat: 0,lng: 0};
  }
  if(location.lat > 0 && location.lng > 0 && isFlush==0){
    callback(location);
    return;
  }
  
  wx.getLocation({
    type: 'gcj02',
    success(res) {
      console.log('获取定位',res);
      if (res.latitude != null && res.latitude != undefined) {
        location.lat = res.latitude;
      }
      if (res.longitude != null && res.longitude != undefined) {
        location.lng = res.longitude;
      } 
      wx.setStorageSync('location', location);
      callback(location);
    },
    fail(res) {
      console.log('获取定位失败',res)
      wx.setStorageSync('location', location);
      callback(location);
    }
  })
}

//从缓存中获取当前名片
function getStaffIdByUid(callback){
  const app = getApp();
  if(app && app.globalData.staff){
    if(app.globalData.staff.Uid == app.globalData.userInfo.Uid){
      console.log('缓存中读取名片')
      callback(app.globalData.staff);
      return;
    }
  }
  if(app && app.globalData.userInfo){
    wx.request({
      url: app.globalData.host + '/api/staff/GetStaffIdByUid?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          console.log('名片设置成功');
          app.globalData.staff = res.data.Data;
          callback(app.globalData.staff);
        } else{
          showModal(res.data.Message)
        }
      },
    })
  }else{
    setTimeout(function () {
      getStaffIdByUid(callback)
    }, 1000)
  }  
}

//从缓存中获取当前名片
function getStaff(callback){
  const app = getApp();
  let cardId = wx.getStorageSync("cardId");  //当前显示的名片
  if(app && app.globalData.staff.Id > 0 && app.globalData.staff.Id == cardId){
    console.log('缓存中读取名片')
    callback(app.globalData.staff);
    return;
  }  
  
  wx.request({
    url: app.globalData.host + '/api/staff/GetStaff?id=' + cardId,
    success: function (res) {
      if (res.data.Code == 0) {
        console.log('名片设置成功');
        app.globalData.staff = res.data.Data;
        callback(res.data.Data);
      } else{
        showModal(res.data.Message)
      }
    },
  })
}

//自动登录
function authLogin(callback){
  let app=getApp();
  let index = 0;
  if(app.globalData.userInfo){
    callback();
    return;
  }
  let timer = setInterval(()=>{
    index ++;
    if(index>=10 || app.globalData.userInfo!=null){
      clearInterval(timer);      
      callback();
    }
  },300);
}
module.exports = {
  wxPromisify: wxPromisify,
  formatTime: formatTime,
  vailPhone: vailPhone,
  authori: authori,
  aiCardActionRecord: aiCardActionRecord,
  getCurrentToday: getCurrentToday,
  dateLater: dateLater,
  compareDate: compareDate,
  getMobile: getMobile,
  formatAvater: formatAvater,
  formatAvaterByProHead: formatAvaterByProHead,
  getCurrentTodayDate: getCurrentTodayDate,
  recordActionTime: recordActionTime,
  checkChoseImages: checkChoseImages,
  setNavBarTitle: setNavBarTitle,
  getNavBarTitle: getNavBarTitle,
  getMobileSysInfo: getMobileSysInfo,
  jiaDate: jiaDate,
  jianDate: jianDate,
  isAccredit: isAccredit,
  subscribe: subscribe,
  getMsgUnRead: getMsgUnRead,
  tapChatFrom: tapChatFrom,
  toCloseSocket: toCloseSocket,
  copyData: copyData,
  AuthorizeUserInfo: AuthorizeUserInfo,
  AuthorizeUserInfoOld: AuthorizeUserInfoOld,
  getQuery: getQuery,
  showModal: showModal,
  showToast: showToast,
  confirm: confirm,
  getLocation: getLocation,
  getStaffIdByUid: getStaffIdByUid,
  getStaff: getStaff,
  authLogin: authLogin
}